package com.main.common.interceptors;

import com.main.common.enums.LimitType;
import com.main.common.interfaces.AccessLimit;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
public class AccessLimitInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(LocalDateTime.now());
        System.out.println("AccessLimitInterceptor");
        // 在控制器执行之前执行一些操作
        System.out.println("------------------AccessLimitInterceptor--------------------");
        System.out.println(request);
       if(isOverLimit(request)){
           response.setStatus(HttpServletResponse.SC_FORBIDDEN);
           return false;
       }
       return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(LocalDateTime.now());
        System.out.println("AccessLimitInterceptor");
        // 在控制器执行之后，视图渲染之前执行一些操作
        System.out.println("------------------AccessLimitInterceptor--------------------");
        System.out.println(request);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求结束之后执行一些操作
        System.out.println("AccessLimitInterceptor after completion...");
    }

    private boolean isOverLimit(HttpServletRequest request) {
        String uri = request.getRequestURI();
        return uri.endsWith("/robots.txt");
    }

    private int getAccessLimit(HttpServletRequest request) {
        String uri = request.getRequestURI();
        return uri.lastIndexOf("robots.txt");
    }
}
